package com.lear.njava.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lear.njava.mapper.TeacherMapper;
import com.lear.njava.pojo.LoginForm;
import com.lear.njava.pojo.Teacher;
import com.lear.njava.service.TeacherService;
import com.lear.njava.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Override
    public Teacher login(LoginForm loginForm) {
        // 创建QueryWrapper对象
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<Teacher>();
        // 拼接查询条件
        queryWrapper.eq("name", loginForm.getUsername());
        // 转换成密文进行查询
        queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        Teacher teacher = baseMapper.selectOne(queryWrapper);
        return teacher;
    }

    @Override
    public Teacher getTeacherById(Long userId) {
        // 创建QueryWrapper对象
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<Teacher>();
        // 判断userId是否等于id
        queryWrapper.eq("id", userId);
        Teacher teacher = baseMapper.selectOne(queryWrapper);
        return teacher;
    }

    @Override
    public IPage<Teacher> getTeachersByOpr(Page<Teacher> pageParam, Teacher teacher) {
        // 创建QueryWrapper包裹查询对象
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<Teacher>();
        // 判断查询条件是否为空
        String name = teacher.getName();
        if (!StringUtils.isEmpty(name)) {
            // 拼接查询条件
            queryWrapper.like("name", name);
        }
        String clazzName = teacher.getClazzName();
        if (!StringUtils.isEmpty(clazzName)) {
            // 拼接查询条件
            queryWrapper.eq("clazz_name", clazzName);
        }
        queryWrapper.orderByDesc("id");
        // 通过baseMapper进行查询
        Page<Teacher> teacherPage = baseMapper.selectPage(pageParam, queryWrapper);
        return teacherPage;
    }
}
